package com.browser.security;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.HashSet;
import java.util.Set;
import java.util.regex.Pattern;

public class SecurityManager {
    private static final Logger logger = LoggerFactory.getLogger(SecurityManager.class);
    
    private final Set<String> blockedDomains;
    private final Pattern maliciousUrlPattern;
    private final CookieManager cookieManager;
    private final PermissionManager permissionManager;

    public SecurityManager() {
        this.blockedDomains = new HashSet<>();
        this.maliciousUrlPattern = Pattern.compile(
            "(?i).*(phishing|malware|virus|trojan|malicious).*"
        );
        this.cookieManager = new CookieManager();
        this.permissionManager = new PermissionManager();
        
        initializeBlockedDomains();
    }

    private void initializeBlockedDomains() {
        // 添加一些已知的恶意域名
        blockedDomains.add("malware.com");
        blockedDomains.add("phishing.example.com");
    }

    public boolean isUrlSafe(String url) {
        logger.debug("Checking URL safety: {}", url);
        
        // 检查是否是已知的恶意域名
        String domain = extractDomain(url);
        if (blockedDomains.contains(domain)) {
            logger.warn("Blocked domain detected: {}", domain);
            return false;
        }
        
        // 检查URL是否包含可疑关键词
        if (maliciousUrlPattern.matcher(url).matches()) {
            logger.warn("Suspicious URL pattern detected: {}", url);
            return false;
        }
        
        return true;
    }

    private String extractDomain(String url) {
        try {
            return new java.net.URL(url).getHost().toLowerCase();
        } catch (Exception e) {
            return url;
        }
    }

    public void blockDomain(String domain) {
        blockedDomains.add(domain.toLowerCase());
    }

    public void unblockDomain(String domain) {
        blockedDomains.remove(domain.toLowerCase());
    }

    public CookieManager getCookieManager() {
        return cookieManager;
    }

    public PermissionManager getPermissionManager() {
        return permissionManager;
    }
} 